package com.baizhi.realm;

import com.baizhi.dao.AdminDAO;
import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
//    获取授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        获取用户名getPrimaryPrincipal主身份信息
        String username = (String) principals.getPrimaryPrincipal();
//        根据用户名  获取用户相关的角色信息和权限信息
        Set<String> role = adminService.selectOneRole(username);
        Set<String> resource = adminService.selectResource(username);
//        封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        设置自定义的角色信息
        info.setRoles(role);
//        设置自定义的权限信息
        info.setStringPermissions(resource);
        return info;
    }
//    获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//      获取令牌的用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
//      从令牌中获取用户名
        String username = usernamePasswordToken.getUsername();
        Admin admin = adminService.selectOne(username);
//        判断用户是否为空
        if(admin != null){
//          第一个参数  当前用户对象的名字
//          第二个参数  当前用户对象的密码
//          第三个参数  当前对象的名字
            return new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),this.getName());
        }

        return null;
    }
}
